#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen@163.com
@file: role.py
@time: 2023/11/17 13:12
@desc: 
"""
# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen@163.com
@file: menu.py
@time: 2023/11/14 19:24
@desc: 
"""

from backend.tvadmin.system.models.factory import Factory
from backend.tvadmin.system.models.permission import Menu, Role
from backend.tvadmin.utils.base_requeset import BaseAuthCheckHttpHandler
from backend.tvadmin.utils.base_response import SuccessResponse, ErrorResponse
from backend.tvadmin.utils.page_utils import self_pagination


class RoleModelViewSet(BaseAuthCheckHttpHandler):
    """
    角色管理
    """

    def get(self, *args, **kwargs):
        if hasattr(self.request, "data"):
            result = Role.filter_list(self.request.data)
        else:
            result = Role.all_list()
        data = self_pagination(self.request, data_list=result)
        return self.write(SuccessResponse(data))

    def post(self, *args, **kwargs):
        """
        角色添加
        """
        role = Role()
        role.name = self.request.data.get("name")
        role.role_key = self.request.data.get("role_key")
        role.status = self.request.data.get("status")
        role.is_admin = self.request.data.get("is_admin")
        menus = self.request.data.get("menus", [])
        if menus:
            menus = Menu.filter_in(key="id", filter=menus)
            role.menu = menus
        role = Role.add(role, self.request)
        return self.write(SuccessResponse(role))

    def put(self, *args, **kwargs):
        id = self.request.data.get("id")
        if id:
            role = Role.first(id=id)
            if role:
                role.name = self.request.data.get("name")
                role.role_key = self.request.data.get("role_key")
                role.status = self.request.data.get("status")
                role.is_admin = self.request.data.get("is_admin")
                menus = self.request.data.get("menus", [])
                if menus:
                    menus = Menu.filter_in(key="id", filter=menus)
                    role.menu = menus
                    Role.save(role)
                return self.write(SuccessResponse())

    def delete(self, *args, **kwargs):
        id = self.request.data.get("id")
        role = Role.first(id=id)
        if role:
            Role.delete_soft(id=id)
            return self.write(SuccessResponse(data=[]))
        else:
            return self.write(ErrorResponse(msg="角色不存在"))
